package com.hjj.controller;

import com.hjj.beans.Activity;
import com.hjj.beans.User;
import com.hjj.dto.ResultDTO;
import com.hjj.dto.ResultPageDTO;
import com.hjj.exception.CRUDException;
import com.hjj.services.ActivityServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@RestController
@RequestMapping("/Activity")
public class ActivityController {

    @Autowired
    ActivityServices activityServices;

    @RequestMapping("getAll.action")
    public ResultPageDTO getAll(ResultPageDTO resultPageDTO){
        // 获取所有市场活动的数据
        ArrayList<Activity> all = activityServices.getAll(resultPageDTO);

        // 将获取到是市场活动数据添加到DTO中
        resultPageDTO.setData(all);

        return resultPageDTO;
    }


    @RequestMapping("getIdAndRemark.action")
    public Activity getIdAndRemark(String id){
        return activityServices.getIdAndRemark(id);
    }

    @RequestMapping("add.action")
    public ResultDTO add(Activity activity, HttpSession httpSession) throws CRUDException {
        // 获取当前登录的用户
        User user = (User) httpSession.getAttribute("user");
        activity.setCreateBy(user.getName());

        // 调用添加业务
        boolean add = activityServices.add(activity);

        if (!add) throw new CRUDException("市场活动信息添加失败");

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);

        return resultDTO;
    }


    @RequestMapping("editBefore.action")
    public Activity editBefore(String id){
        return  activityServices.editBefore(id);
    }

    @RequestMapping("edit.action")
    public ResultDTO edit(Activity activity, HttpSession httpSession) throws CRUDException {
        // 获取当前登录的用户
        User user = (User) httpSession.getAttribute("user");
        activity.setEditBy(user.getName());

        // 调用添加业务
        boolean edit = activityServices.edit(activity);

        if (!edit) throw new CRUDException("市场活动信息修改失败");

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);

        return resultDTO;
    }

    @RequestMapping("del.action")
    public ResultDTO del(@RequestBody String[] ids) throws CRUDException {

        boolean del = activityServices.del(ids);

        if (!del) throw new CRUDException("市场活动数据删除失败");


        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);
        return resultDTO;
    }
}

